package com.yookey.study;

import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;


import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.BaseApp;
import com.base.commonlib.base.CBaseMvpActivity;

import com.base.commonlib.bean.StatEntity;
import com.base.commonlib.bean.User;
import com.base.commonlib.event.StudyEvent;
import com.base.commonlib.http.RealNetWorkUtil;
import com.base.commonlib.http.utils.CallBackImpl;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.SystemUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.commonlib.widget.CommonDialog;
import com.base.commonlib.widget.CommonSingleDialog;
import com.base.look.bean.StatEntity2;
import com.base.look.fragment.LookFragment;
import com.base.mine.bean.Version;
import com.base.mine.config.RouteConfig;
import com.base.study.fragment.StudyFragment;
import com.base.sweb.ExaminationFragment;
import com.base.work.WorkFragment;
import com.yookey.study.bean.HomeStatEntity;
import com.yookey.study.bean.VoiceEvent;
import com.yookey.study.databinding.ActivityMainBinding;


import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.disposables.CompositeDisposable;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;
import me.yokeyword.fragmentation.SupportFragment;


@Route(path = "/study/home")
public class MainActivity extends CBaseMvpActivity {
    protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    //退出点击次数
    protected int times = 1;

    private ActivityMainBinding mBinding;
    private List<SupportFragment> mFragments;
    private SupportFragment mCurrentFragment;

    @Autowired
    int type;
    @Autowired
    int num;
    @Override
    protected int getLayoutResource() {
        return R.layout.activity_main;

    }

    @Override
    protected void init() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(getResources().getColor(R.color.color_4486FF));
                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mBinding =  (ActivityMainBinding)mRootBinding;
    }

    @Override
    protected void start() {
        initFragment();
        initBottomTab();
        checkVersion();
        if (type==1){
            ARouter.getInstance().build("/changepw/pw").withInt("type",1).navigation();
        }
        if (num==2){
            getJifeng();
        }
    }
    /**
     * 积分
     */
    public void getJifeng(){
        Map<String, Object> map = new HashMap<>();
        map.put("settingKey","08020003");
        map.put("funcMainId", "edu");
        Disposable enqueue = RealNetWorkUtil.postContent().method("api-function/integral/save").content(map)
                .build().enqueue(String.class, new CallBackImpl<String>() {
                    @Override
                    public void onError(int code, String msg, String errMsg) {
                    }

                    @Override
                    public void onNext(String str) {
                        if (!str.contains("上限")){
                            showMes(str);
                        }

                    }
                });

        mCompositeDisposable.add(enqueue);
    }

    private void initFragment() {
        mFragments = new ArrayList<>();
        mFragments.add(new MainFragment());
        mFragments.add(new StudyFragment());
        //mFragments.add(new MyStudyFragment());
        //mFragments.add(new StudyDoubleListFragment());
        mFragments.add(new ExaminationFragment());
        mFragments.add(new WorkFragment());
        mFragments.add(new LookFragment());
        //mFragments.add(new ConstractFragment());
//        mFragments.add(new MineFragment());
        mCurrentFragment = mFragments.get(0);
        //默认选中第一个
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.recycler, mFragments.get(0), mFragments.get(0).getClass().getName());
        transaction.commitAllowingStateLoss();
    }


    private void initBottomTab() {
        final NavigationController navigationController = mBinding.pagerBottomTab.material()
                .addItem(R.mipmap.ic_home, R.mipmap.icon_home_s, getString(R.string.main))
                .addItem(R.mipmap.icon_study, R.mipmap.ic_study_s, getString(R.string.study))
                .addItem(R.mipmap.icon_mine, R.mipmap.icon_mine, getString(R.string.mine))
                .addItem(R.mipmap.icon_work, R.mipmap.icon_work, getString(R.string.work))
                .addItem(R.mipmap.icon_u_look, R.mipmap.icon_look, getString(R.string.look))
                .setDefaultColor(ContextCompat.getColor(mContext, R.color.textColorVice))
                .build();
        //底部按钮的点击事件监听
        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                FragmentManager manager = getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                if (manager.findFragmentByTag(mFragments.get(index).getClass().getName()) != null) {
                    transaction.show(mFragments.get(index));
                } else {
                    transaction.add(R.id.recycler, mFragments.get(index), mFragments.get(index).getClass().getName());
                }
                transaction.hide(mCurrentFragment);
                mCurrentFragment = mFragments.get(index);
//                transaction.replace(R.id.recycler, mFragments.get(index));
                transaction.commitAllowingStateLoss();
            }

            @Override
            public void onRepeat(int index) {
                RxBus2.getInstance().post(new HomeStatEntity(1));
            }
        });

        Disposable disposable = RxBus2.getInstance().doSubscribe(StatEntity.class, new Consumer<StatEntity>() {
            @Override
            public void accept(StatEntity bean) throws Exception {
               if (bean.getState()==1){
                   setLightStatusBar(MainActivity.this, false);
                   try {
                       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                           Window window = getWindow();
                           window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                           window.setStatusBarColor(getResources().getColor(R.color.color_4486FF));
                           //底部导航栏
                           //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
                       }
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }else {
                   setLightStatusBar(MainActivity.this, true);
                   try {
                       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                           Window window = getWindow();
                           window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                           window.setStatusBarColor(getResources().getColor(R.color.color_white));
                           //底部导航栏
                           //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
                       }
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable);

        Disposable disposable1 = RxBus2.getInstance().doSubscribe(StudyEvent.class, new Consumer<StudyEvent>() {
            @Override
            public void accept(StudyEvent bean) throws Exception {
                navigationController.setSelect(bean.getSelectCurrent());
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable1);
    }

    private void checkVersion(){
        showPb();
        HashMap<String, String> param = new HashMap<>();
        param.put("appVersion", SystemUtil.packageName(mContext));
        param.put("versionCode", SystemUtil.getVersionCode(mContext)+"");
        param.put("appName", getString(com.base.mine.R.string.app_name));
        Disposable disposable = RealNetWorkUtil.postContent()
                .method("api-basic/app/check")
                .content(param)
                .build().enqueue(Version.class, new CallBackImpl<Version>() {
                    @Override
                    public void onError(int code, String msg, String errMsg) {
                        hidePb();
                        if (!TextUtils.isEmpty(msg)) {
                            showMes(msg);
                        }
                    }
                    @Override
                    public void onNext(Version version) {
                        hidePb();
                        if (version.isHaveNewVersion()){
                            CommonSingleDialog commonDialog = new CommonSingleDialog(mContext, "您有新版本：\n"+version.getDescription());
                            commonDialog.setOnPosClick(new CommonSingleDialog.OnPosClick() {
                                @Override
                                public void onClick() {
                                    ARouter.getInstance().build(RouteConfig.ACTIVITY_VERSION).navigation();
                                }
                            });
                            commonDialog.setCancelable(false);
                            commonDialog.show();
                        }
                    }
                });
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void onBackPressedSupport() {
        Timer timer = null;
        if (times == 1) {
            times++;
            ToastUtil.show("再按一次退出应用!");
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    times = 1;
                }
            }, 2000);
        } else {
            //stopService();
            BaseApp.exit();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.dispose();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //次数因为LookFragment中 onActivityResult 不生效 所以supe.onActivityResult
        super.onActivityResult(requestCode, resultCode, data);
        VoiceEvent voiceEvent = new VoiceEvent();
        voiceEvent.setData(data);
        voiceEvent.setRequestCode(requestCode);
        voiceEvent.setResultCode(resultCode);
        RxBus2.getInstance().post(voiceEvent);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        RxBus2.getInstance().post(ev);
        return super.dispatchTouchEvent(ev);
    }
}
